package com.fish.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Slf4j
@Component
public class RedisUtil {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    // =============================String=============================
    
    /**
     * 设置缓存
     */
    public void set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("Redis set error, key: {}", key, e);
        }
    }
    
    /**
     * 设置缓存并设置过期时间
     */
    public void set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
        } catch (Exception e) {
            log.error("Redis set with expire error, key: {}", key, e);
        }
    }
    
    /**
     * 获取缓存
     */
    public Object get(String key) {
        try {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("Redis get error, key: {}", key, e);
            return null;
        }
    }
    
    /**
     * 删除缓存
     */
    public Boolean delete(String key) {
        try {
            return redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("Redis delete error, key: {}", key, e);
            return false;
        }
    }
    
    /**
     * 批量删除缓存
     */
    public Long delete(Collection<String> keys) {
        try {
            return redisTemplate.delete(keys);
        } catch (Exception e) {
            log.error("Redis batch delete error, keys: {}", keys, e);
            return 0L;
        }
    }
    
    /**
     * 判断key是否存在
     */
    public Boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("Redis hasKey error, key: {}", key, e);
            return false;
        }
    }
    
    /**
     * 设置过期时间
     */
    public Boolean expire(String key, long time) {
        try {
            if (time > 0) {
                return redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return false;
        } catch (Exception e) {
            log.error("Redis expire error, key: {}", key, e);
            return false;
        }
    }
    
    /**
     * 获取过期时间
     */
    public Long getExpire(String key) {
        try {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("Redis getExpire error, key: {}", key, e);
            return -2L;
        }
    }
    
    /**
     * 递增
     */
    public Long increment(String key, long delta) {
        try {
            return redisTemplate.opsForValue().increment(key, delta);
        } catch (Exception e) {
            log.error("Redis increment error, key: {}", key, e);
            return null;
        }
    }
    
    /**
     * 递减
     */
    public Long decrement(String key, long delta) {
        try {
            return redisTemplate.opsForValue().decrement(key, delta);
        } catch (Exception e) {
            log.error("Redis decrement error, key: {}", key, e);
            return null;
        }
    }
    
    // =============================Set=============================
    
    /**
     * 向Set中添加元素
     */
    public Long setAdd(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error("Redis setAdd error, key: {}", key, e);
            return 0L;
        }
    }
    
    /**
     * 获取Set中的所有元素
     */
    public Set<Object> setMembers(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error("Redis setMembers error, key: {}", key, e);
            return new HashSet<>();
        }
    }
    
    /**
     * 判断元素是否在Set中
     */
    public Boolean setIsMember(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            log.error("Redis setIsMember error, key: {}", key, e);
            return false;
        }
    }
    
    /**
     * 从Set中移除元素
     */
    public Long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            log.error("Redis setRemove error, key: {}", key, e);
            return 0L;
        }
    }
    
    // =============================Hash=============================
    
    /**
     * 向Hash中添加数据
     */
    public void hashPut(String key, String hashKey, Object value) {
        try {
            redisTemplate.opsForHash().put(key, hashKey, value);
        } catch (Exception e) {
            log.error("Redis hashPut error, key: {}, hashKey: {}", key, hashKey, e);
        }
    }
    
    /**
     * 从Hash中获取数据
     */
    public Object hashGet(String key, String hashKey) {
        try {
            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception e) {
            log.error("Redis hashGet error, key: {}, hashKey: {}", key, hashKey, e);
            return null;
        }
    }
    
    /**
     * 获取Hash中所有数据
     */
    public Map<Object, Object> hashGetAll(String key) {
        try {
            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            log.error("Redis hashGetAll error, key: {}", key, e);
            return new HashMap<>();
        }
    }
    
    /**
     * 从Hash中删除数据
     */
    public Long hashDelete(String key, Object... hashKeys) {
        try {
            return redisTemplate.opsForHash().delete(key, hashKeys);
        } catch (Exception e) {
            log.error("Redis hashDelete error, key: {}", key, e);
            return 0L;
        }
    }
    
    /**
     * 判断Hash中是否存在指定字段
     */
    public Boolean hashHasKey(String key, String hashKey) {
        try {
            return redisTemplate.opsForHash().hasKey(key, hashKey);
        } catch (Exception e) {
            log.error("Redis hashHasKey error, key: {}, hashKey: {}", key, hashKey, e);
            return false;
        }
    }
    
    // =============================List=============================
    
    /**
     * 向List右侧添加元素
     */
    public Long listRightPush(String key, Object value) {
        try {
            return redisTemplate.opsForList().rightPush(key, value);
        } catch (Exception e) {
            log.error("Redis listRightPush error, key: {}", key, e);
            return 0L;
        }
    }
    
    /**
     * 获取List指定范围的元素
     */
    public List<Object> listRange(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error("Redis listRange error, key: {}", key, e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取List的长度
     */
    public Long listSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error("Redis listSize error, key: {}", key, e);
            return 0L;
        }
    }
    
    /**
     * 根据通配符删除key
     */
    public Set<String> keys(String pattern) {
        try {
            return redisTemplate.keys(pattern);
        } catch (Exception e) {
            log.error("Redis keys error, pattern: {}", pattern, e);
            return new HashSet<>();
        }
    }
    
    /**
     * 根据通配符批量删除key
     */
    public Long deleteByPattern(String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern);
            if (keys != null && !keys.isEmpty()) {
                return redisTemplate.delete(keys);
            }
            return 0L;
        } catch (Exception e) {
            log.error("Redis deleteByPattern error, pattern: {}", pattern, e);
            return 0L;
        }
    }
    
    /**
     * 删除缓存（别名方法）
     */
    public Boolean del(String key) {
        return delete(key);
    }
}